<?php
// +----------------------------------------------------------------------
// | 公共函数
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2017 Even Yin All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Even yin <416467069@qq.com> <13022156261>
// +----------------------------------------------------------------------
\think\Loader::addNamespace('core','../core/');


use think\Config;
use Wechat\Loader;
function & load_wechat($type = '') {
		static $wechat = array();
		$index = md5(strtolower($type));
		if (!isset($wechat[$index])) {
				$config = Config::get('wechat');
				$config['cachepath'] = CACHE_PATH . 'Data/';
				$wechat[$index] = Loader::get($type, $config);
		}
		return $wechat[$index];
}


	function getRandomStr($length=8){
		$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		$str = '';
		for ( $i = 0; $i < $length; $i++ )
		{
		// 这里提供两种字符获取方式
		// 第一种是使用 substr 截取$chars中的任意一位字符；
		// 第二种是取字符数组 $chars 的任意元素
		// $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
			$str .= $chars[ mt_rand(0, strlen($chars) - 1) ];
		}
		return $str;
	}

	function getRandomNum($length='6'){
		$chars = '0123456789';
		$str = '';
		for ( $i = 0; $i < $length; $i++ )
		{
		// 这里提供两种字符获取方式
		// 第一种是使用 substr 截取$chars中的任意一位字符；
		// 第二种是取字符数组 $chars 的任意元素
		// $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
			$str .= $chars[ mt_rand(0, strlen($chars) - 1) ];
		}
		return $str;
	}


	/**
	 *	时间搓相减，剩余日，时，分，秒。
	 */
	function timediff($begin_time,$end_time)
	{
	      if($begin_time < $end_time){
	         $starttime = $begin_time;
	         $endtime = $end_time;
	      }else{
	         $starttime = $end_time;
	         $endtime = $begin_time;
	      }
	      //计算天数
	      $timediff = $endtime-$starttime;
	      $days = intval($timediff/86400);
	      //计算小时数
	      $remain = $timediff%86400;
	      $hours = intval($remain/3600);
	      //计算分钟数
	      $remain = $remain%3600;
	      $mins = intval($remain/60);
	      //计算秒数
	      $secs = $remain%60;
	      $res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs);
	      return $res;
	}

	/**
	 * 获取微信操作对象
	 * @staticvar array $wechat
	 * @param type $type
	 * @return WechatReceive
	 */

	/**
	 * *
	 * 获取图片路径
	 *
	 * */
	function getTrueUrl($url){
//		$is_true = preg_match('/^http[s]?:\/\/'.
//			    			'(([0-9]{1,3}\.){3}[0-9]{1,3}'. // IP形式的URL- 199.194.52.184
//			    			'|'. // 允许IP和DOMAIN（域名）
//			    			'([0-9a-z_!~*\'()-]+\.)*'. // 域名- www.
//			    			'([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.'. // 二级域名
//			    			'[a-z]{2,6})'.  // first level domain- .com or .museum
//			    			'(:[0-9]{1,4})?'.  // 端口- :80
//			    			'((\/\?)|'.  // a slash isn't required if there is no file name
//			    			'(\/[0-9a-zA-Z_!~\'
//						\.;\?:@&=\+\$,%#-\/^\*\|]*)?)$/',
//  			$url) == 1;

    		if(preg_match('/^http[s]?:\/\/.*$/',$url)) return $url;

//  		if($is_ture) return $url;
    		return 'http://jjx.qianbeinet.com'.$url;
	}
	/*
	  16-19 位卡号校验位采用 Luhm 校验方法计算：
	    1，将未带校验位的 15 位卡号从右依次编号 1 到 15，位于奇数位号上的数字乘以 2
	    2，将奇位乘积的个十位全部相加，再加上所有偶数位上的数字
	    3，将加法和加上校验位能被 10 整除。
	*/
	function luhm($no) {
		$arr_no = str_split($no);
		$last_n = $arr_no[count($arr_no)-1];
		krsort($arr_no);
		$i = 1;
		$total = 0;
		foreach ($arr_no as $n){
		    if($i%2==0){
		        $ix = $n*2;
		        if($ix>=10){
		            $nx = 1 + ($ix % 10);
		            $total += $nx;
		        }else{
		            $total += $ix;
		        }
		    }else{
		        $total += $n;
		    }
		    $i++;
		}
		$total -= $last_n;
		$total *= 9;
		if($last_n == ($total%10)){
		    return true;
		}
		return false;
	}

	function bankInfo($card)
	{
		$bankList = Config::get('banklist');
	    $card_8 = substr($card, 0, 8);
	    if (isset($bankList[$card_8])) {
	        return $bankList[$card_8];
	    }
	    $card_6 = substr($card, 0, 6);
	    if (isset($bankList[$card_6])) {
	        return $bankList[$card_6];
	    }
	    $card_5 = substr($card, 0, 5);
	    if (isset($bankList[$card_5])) {
	        return $bankList[$card_5];
	    }
	    $card_4 = substr($card, 0, 4);
	    if (isset($bankList[$card_4])) {
	        return $bankList[$card_4];
	    }
	    return '该卡号信息暂未录入';
	}


   function gmt_iso8601($time) {
        $dtStr = date("c", $time);
        $mydatetime = new DateTime($dtStr);
        $expiration = $mydatetime->format(DateTime::ISO8601);
        $pos = strpos($expiration, '+');
        $expiration = substr($expiration, 0, $pos);
        return $expiration."Z";
    }
	function closetags($html) {
		// 不需要补全的标签
		$arr_single_tags = array('meta', 'img', 'br', 'link', 'area');
		// 匹配开始标签
		preg_match_all('#<([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
		$openedtags = $result[1];
		// 匹配关闭标签
		preg_match_all('#</([a-z]+)>#iU', $html, $result);
		$closedtags = $result[1];
		// 计算关闭开启标签数量，如果相同就返回html数据
		$len_opened = count($openedtags);
		if (count($closedtags) == $len_opened) {
		return $html;
		}
		// 把排序数组，将最后一个开启的标签放在最前面
		$openedtags = array_reverse($openedtags);
		// 遍历开启标签数组
		for ($i = 0; $i < $len_opened; $i++) {
		// 如果需要补全的标签
		if (!in_array($openedtags[$i], $arr_single_tags)) {
		// 如果这个标签不在关闭的标签中
		if (!in_array($openedtags[$i], $closedtags)) {
		// 直接补全闭合标签
		$html .= '</' . $openedtags[$i] . '>';
		} else {
		unset($closedtags[array_search($openedtags[$i], $closedtags)]);
		}
		}
		}
		return $html;
	}
	/**
	 * 前台获取微信二维码url。
	 *
	 */
	function getWechatLoginQR(){
		$sessionId = md5('wechat'.session_id());
		$url = request()->domain().'/member/wechatlogin/action/login.html?id='.$sessionId;
		return $url;
	}

	function isWechat(){
		$agent = $_SERVER['HTTP_USER_AGENT'];
		if(preg_match('/micromessenger/i',$agent)){
			preg_match('/.*?(MicroMessenger\/([0-9.]+))\s*/', $agent, $matches);
			return ['code'=>1,'version'=>$matches[2]];
		}
		return false;
	}

	function getClient() {
		$browser = array();
		$browser['model'] = '';
		$browser['browser'] = '';
		$browser['address'] = '';
		$agent = $_SERVER['HTTP_USER_AGENT'];
		$regex = array(
			'model' => array(
						'windows' => '/win/i',
						'mac' => '/mac/i',
						'linux' => '/linux/i',
						'mobile' => '/mobile/i',
						'wechat' => '/micromessenger/i',
					),
			'browser'=> array(
						'ie'      => '/(MSIE) (\d+\.\d)/',
	        				'chrome'  => '/(Chrome)\/(\d+\.\d+)/',
	        				'firefox' => '/(Firefox)\/(\d+\.\d+)/',
	        				'opera'   => '/(Opera)\/(\d+\.\d+)/',
	        				'safari'  => '/Version\/(\d+\.\d+\.\d) (Safari)/',
					)
		);
		foreach($regex as $k => $v){
			foreach($v as $kk => $vv){
				if(preg_match($vv,$agent)){
					$browser[$k] = $kk;
				}
			}
		}
	    $ip = request()->ip();
	   	$ipadd = file_get_contents("http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=".$ip);//根据新浪api接口获取
	   	if($ipadd){
	    		$charset = iconv("gbk","utf-8",$ipadd);
	    		preg_match_all("/[\x{4e00}-\x{9fa5}]+/u",$charset,$ipadds);
	    		$ipadds = implode(' ',$ipadds[0]);
	    		$browser['address'] = $ipadds;
	   	}

		return $browser;
	}
	/**
	 * 获取客户端浏览器类型
	 * @param  string $glue 浏览器类型和版本号之间的连接符
	 * @return string|array 传递连接符则连接浏览器类型和版本号返回字符串否则直接返回数组 false为未知浏览器类型
	 */
	function get_client_browser($glue = null) {
	    $browser = array();
	    $agent = $_SERVER['HTTP_USER_AGENT']; //获取客户端信息

	    /* 定义浏览器特性正则表达式 */
	    $regex = array(
	        'ie'      => '/(MSIE) (\d+\.\d)/',
	        'chrome'  => '/(Chrome)\/(\d+\.\d+)/',
	        'firefox' => '/(Firefox)\/(\d+\.\d+)/',
	        'opera'   => '/(Opera)\/(\d+\.\d+)/',
	        'safari'  => '/Version\/(\d+\.\d+\.\d) (Safari)/',
	    );
	    foreach($regex as $type => $reg) {
	        preg_match($reg, $agent, $data);
	        if(!empty($data) && is_array($data)){
	            $browser = $type === 'safari' ? array($data[2], $data[1]) : array($data[1], $data[2]);
	            break;
	        }
	    }
	    return empty($browser) ? false : (is_null($glue) ? $browser : implode($glue, $browser));
	}
	function getOs(){
	   if(!empty($_SERVER['HTTP_USER_AGENT'])){
		    $OS = $_SERVER['HTTP_USER_AGENT'];
		      if (preg_match('/win/i',$OS)) {
		     $OS = 'Windows';
		    }elseif (preg_match('/mac/i',$OS)) {
		     $OS = 'MAC';
		    }elseif (preg_match('/linux/i',$OS)) {
		     $OS = 'Linux';
		    }elseif (preg_match('/unix/i',$OS)) {
		     $OS = 'Unix';
		    }elseif (preg_match('/bsd/i',$OS)) {
		     $OS = 'BSD';
		    }else {
		     $OS = 'Other';
		    }
	        return $OS;
	    }
	   	return false;
	}
	//根据ip获得访客所在地地名
  	function getAddress($ip=''){
	   if(empty($ip)){
	       $ip = request()->ip();
	   }
	   $ipadd = file_get_contents("http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=".$ip);//根据新浪api接口获取
	   if($ipadd){
	    		$charset = iconv("gbk","utf-8",$ipadd);
	    		preg_match_all("/[\x{4e00}-\x{9fa5}]+/u",$charset,$ipadds);
	    		return $ipadds;   //返回一个二维数组
	   }else{return false;}
  	}

  	function getNewsTag($id=''){
  		if($id!=''){
  			return model('NewsTag')->get($id);
  		}
  		$list = model('NewsTag')->select();
  		return $list;
  	}

  	function getNewsCategoryBother($id=''){
  		$pid = model('NewsCategory')->where(['id'=>$id])->column('pid');
  		return model('NewsCategory')->where(['pid'=>$pid])->select();
  	}

  	function getNewsCategory($id='',$pid=''){
  		if($id!=''){
  			$where['id'] = $id;
  		}
  		if($pid!==''){
  			$where['pid'] = $pid;
  		}
  		if($id==='' && $pid===''){
  			$list = model('NewsCategory')->select();
  		}else{
  			$list = model('NewsCategory')->where($where)->select();
  		}
  		return $list;
  	}

 	function getSellerList(){
		$seller_list = cache('SellerList');
		if(empty($seller_list)){
			$seller_list = model('Seller')->where(['status'=>1])->select();
			cache('SellerList',$seller_list,360);
		}
		return $seller_list;
	}
